package comtgl.demo.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping("/api/zip")
@Tag(name = "下载")
public class ImageZipController {

    @PostMapping
    @Operation(summary = "课程查询接口")
    public void downloadImagesAsZip(HttpServletResponse response) throws IOException {
        List<String> imageUrls = new ArrayList<>();
        imageUrls.add("https://hichatx-test.hisense.com/image/684a4813d08e53ed4a91684f/684a4813d08e53ed4a91684e");
        imageUrls.add("https://hichatx-test.hisense.com/pubacc/public/data/15/07/31/tNTMYIwt.jpg");
        // 创建临时目录
        Path tempDir = Files.createTempDirectory("image_zip_");
        File zipFile = new File(tempDir.toFile(), "images.zip");

        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
            // 下载并添加每个图片到ZIP
            for (int i = 0; i < imageUrls.size(); i++) {
                String url = imageUrls.get(i);
                try {
                    String fileName = generateFileName(url, i);
                    downloadImageToZip(url, fileName, zipOut);
                } catch (Exception e) {
                    // 记录错误但继续处理其他图片
                    System.err.printf("无法下载图片 %s: %s%n", url, e.getMessage());
                }
            }
        } catch (Exception e) {
            // 清理临时文件
            Files.deleteIfExists(zipFile.toPath());
            Files.deleteIfExists(tempDir);
            throw new IOException("创建ZIP文件失败", e);
        }

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=images.zip");

        // 清理临时文件
        Files.deleteIfExists(zipFile.toPath());
        Files.deleteIfExists(tempDir);
    }

    private void downloadImageToZip(String imageUrl, String fileName, ZipOutputStream zipOut) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        try (InputStream in = connection.getInputStream()) {
            ZipEntry zipEntry = new ZipEntry(fileName);
            zipOut.putNextEntry(zipEntry);

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                zipOut.write(buffer, 0, bytesRead);
            }

            zipOut.closeEntry();
        }
    }

    private String generateFileName(String url, int index) {
        String ext = getFileExtension(url);
        return "image_" + index + ext;
    }

    private String getFileExtension(String url) {
        int lastDot = url.lastIndexOf('.');
        if (lastDot > 0 && lastDot < url.length() - 1) {
            String ext = url.substring(lastDot);
            if (ext.equals(".jpg") || ext.equals(".jpeg") ||
                    ext.equals(".png") || ext.equals(".gif") ||
                    ext.equals(".bmp") || ext.equals(".webp")) {
                return ext;
            }
            return ".jpg";
        }
        return ".jpg";
    }
}